﻿using System.Text.RegularExpressions;

namespace Core.Extensions
{
    public static class UrlExtensions
    {
        public static string UrlGetDomain(this string url)
        {
            string pattern = @"(http||https)://([\w\.]+[^/])";
            string s = "";
            var mc = Regex.Matches(url, pattern);
            if (mc is not null && mc.Any() && mc[0].Groups.Count > 2)
                s = mc[0].Groups[2].Value;
            return s;
        }

        public static List<string> UrlGetAllPage(this string url)
        {
            //http://asdf.com/cm/page[1-30:20]
            try
            {
                if (url.IndexOf("[") < 0)
                    return new() { url };
                var range = url.Substring(url.IndexOf("["), url.IndexOf("]") - url.IndexOf("[")+1);
                Regex r = new(@"\d+", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                var mCollection = r.Matches(range);
                List<string> res = new();
                int startPage = 1, endPage = 1, skipPage = 1;
                if (mCollection.Count > 2)
                {
                    int.TryParse(mCollection[0].Value,out startPage);
                    int.TryParse(mCollection[1].Value, out endPage);
                    int.TryParse(mCollection[2].Value, out skipPage);
                }
                else if(mCollection.Count == 2)
                {
                    int.TryParse(mCollection[0].Value, out startPage);
                    int.TryParse(mCollection[1].Value, out endPage);
                }
                else
                {
                    int.TryParse(mCollection[0].Value, out startPage);
                }
                for (int i = startPage; i <= endPage; i+=skipPage)
                {
                    var otherUrl = Regex.Replace(url, @"\[.*\]", i.ToString());
                    res.Add(otherUrl);
                }
                return res;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }
    }
}
